#include "QRScanner.h"
#include <highgui.h>
#include "decodeqr.h"

QRScanner::QRScanner(void)
{
}

QRScanner::~QRScanner(void)
{
}

QRScanner& QRScanner::getInstance(void)
{
	static QRScanner instance;
	return instance;
}

bool QRScanner::initialise(void)
{
	mDisplayScan = false;
	mDecoder = qr_decoder_open();
	mpCapture = cvCaptureFromCAM(0);

	return true;
}

void QRScanner::destroy(void)
{
	qr_decoder_close(mDecoder);
	cvReleaseImage(&mpImage);
	cvDestroyAllWindows();
	//cvReleaseCapture(&mpCapture);
}

void QRScanner::showScanner(void)
{
	mDisplayScan = true;
	cvNamedWindow("QR Scanner",1);
}

void QRScanner::hideScanner(void)
{
	mDisplayScan = false;
	cvDestroyWindow("QR Scanner");
}

void QRScanner::update(void)
{
	try
	{
		mpImage = cvQueryFrame(mpCapture);
		if(mDisplayScan)
		{
			cvShowImage("QR Scanner", mpImage);
		}
	}
	catch(int ex)
	{
	}
}

const char* QRScanner::scan(void)
{
	try
	{
		QrCodeHeader header;
		short status = qr_decoder_decode_image(mDecoder, mpImage, 71);
		if(qr_decoder_get_header(mDecoder, &header))
		{
			char *buf=new char[header.byte_size+1];
			int s = qr_decoder_get_body(mDecoder,(unsigned char *)buf,header.byte_size+1);
			
			if(s > 0 && s < 5)
			{
				return buf;
			}
		}
	}
	catch(int ex)
	{
	}

	return NULL;
}